<?php
namespace app\api\controller;

ini_set("display_errors", "on");
require  app()->getRootPath().'/vendor/Aliyun/api_sdk/vendor/autoload.php';

use think\Controller;

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;

// 加载区域结点配置
Config::load();

class Sms
{
    const APPKEY = 'LTAIPChgadsjsEoB';//key(大于)
    const APPSECRET = 'Uh352V2bYtSIIkzm6LCb9RtWdsjll1';//secret(大于)
    const SMS_2 = 'SMS_158740091';//验证码
    const appProduct = '大旧哥';//应用名称


    public function __construct($accessKeyId = '', $accessKeySecret = '')
    {

//        parent::__construct();
        // 短信API产品名
        $product = "Dysmsapi";

        // 短信API产品域名
        $domain = "dysmsapi.aliyuncs.com";

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";

        // 初始化用户Profile实例
        $profile = DefaultProfile::getProfile($region, Sms::APPKEY, Sms::APPSECRET);

        // 增加服务结点
        DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

        // 初始化AcsClient用于发起请求
        $this->acsClient = new DefaultAcsClient($profile);
    }

    /**
     * 发送短信验证码
     * */
    public function sendCodeSms($mobile, $code)
    {
        if (!preg_match("/^1[345789]{1}\d{9}$/", $mobile)) {
            return false;
        }
//        $code = $this->randCode(4);
        $res = $this->sendSmsCode($mobile, $code);
        if (empty($res)) {
            return false;
        } else {
            return $code;
        }
    }


    private function sendSmsCode($mobile, $code)
    {
        $params = [
            'code' => $code,
        ];
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填，设置雉短信接收号码
        $request->setPhoneNumbers($mobile);
        // 必填，设置签名名称
        $request->setSignName(self::appProduct);
        // 必填，设置模板CODE
//        $request->setTemplateParam(json_encode($params));
        $request->setTemplateParam(json_encode($params));
        $request->setTemplateCode(self::SMS_2);
        // 发起访问请求
        $acsResponse = $this->acsClient->getAcsResponse($request);
        $res = $this->object2array($acsResponse);

        if ($res['Message'] == 'OK' || $res['Code'] == 'OK') {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 发送短信通知
     * @param $mobile
     * @param $sms_id
     * @param $params
     * @return bool
     */
    public function sendSmsMessage($mobile,$sms_id, $params)
    {

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填，设置雉短信接收号码
        $request->setPhoneNumbers($mobile);
        // 必填，设置签名名称
        $request->setSignName(self::appProduct);
        // 必填，设置模板CODE
//        $request->setTemplateParam(json_encode($params));
        $request->setTemplateParam(json_encode($params));
        $request->setTemplateCode($sms_id);
        // 发起访问请求
        $acsResponse = $this->acsClient->getAcsResponse($request);
        $res = $this->object2array($acsResponse);
        halt($res);
        if ($res['Message'] == 'OK' || $res['Code'] == 'OK') {
            return true;
        } else {
            return false;
        }
    }

    function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }

    /**
     * 获取随机位数数字
     * @param  integer $len 长度
     * @return string
     */
    private function randString($len = 4)
    {
        $chars = str_repeat('0123456789', $len);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }

    private function simplexml_obj2array($obj)
    {
        if (count($obj) >= 1) {
            $result = $keys = array();

            foreach ($obj as $key => $value) {
                isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);

                if ($keys[$key] == 1) {
                    $result[$key] = $this->simplexml_obj2array($value);
                } elseif ($keys[$key] == 2) {
                    $result[$key] = array($result[$key], $this->simplexml_obj2array($value));
                } else if ($keys[$key] > 2) {
                    $result[$key][] = $this->simplexml_obj2array($value);
                }
            }
            return $result;
        } else if (count($obj) == 0) {
            return (string)$obj;
        }
    }

    protected function randCode($length = 6)
    {
        return rand(pow(10, ($length - 1)), pow(10, $length) - 1);
    }

}